/*
 * communication.c
 *
 *  Created on: 08.03.2011
 *      Author: nick
 */

#include "communication.h"

void initUart(void) {

    /*
     * Konfiguriere UART2 DEBUG
     */
/*
    U2MODE = 0;
    U2STA = 0;
    U2BRG = BRGVAL;
    U2MODEbits.UARTEN = 1;
    U2STAbits.UTXEN = 1;
*/
    /*
     * Konfiguriere UART1
     * Kommunikation mit Sensor-Master
     */
    U1MODE = 0;
    U1STA = 0;
    U1BRG = BRGVAL;
    U1MODEbits.UARTEN = 1;
    U1STAbits.UTXEN = 0;
}

// send Sensor Data valueMax/Min = [16384, -16383] if the val is bigger/smaller it gets cut off

void sendSensorData(ESensorAdr addr, ESensorValClass valClass, int value, int alarm) {
    char byte1, byte2, byte3;
    //prepare the data
    //Sensoraddr + Valueclass
    byte1 = addr << 4;
    byte1 = byte1 | valClass;
    // Sensorvalue
    //Lowbyte(7Bit) + Alarmflag
    byte2 = value << 1;
    //if the alarm flag is set, set the last bit to 1
    if (alarm)
        byte2 = byte2 | 0x01;
    //Highbyte
    byte3 = value >> 7;
    //check if the value was positiv/negativ and change the sign accordingly
    //TODO integer größe prüfen
    if (value >> 15 == 1)
        byte3 = byte3 | 0x01 << 7;

    //Disable UART1 receiver
    // U1STAbits.URXEN = 0;

        //Enable UART1 Transmitter
    U1STAbits.UTXEN = 1;
    //Send the data
    while(U1STAbits.UTXBF);
    U1TXREG = byte1;
    while(U1STAbits.UTXBF);
    U1TXREG = byte2;
    while(U1STAbits.UTXBF);
    U1TXREG = byte3;

    while(!U1STAbits.TRMT);
    
    //Enable Receiver & Disable Transmitter
    //  U1STAbits.URXEN = 1;
    U1STAbits.UTXEN = 0;

    //über Loopback empfangene Zeichen löschen
    while (DataRdyUART1()) {
        getcUART1();
    }
}
